package com.mylib.libcore.tools;

import android.content.Context;
import android.util.Log;

import com.bun.miitmdid.core.ErrorCode;
import com.bun.miitmdid.core.MdidSdkHelper;
import com.bun.miitmdid.interfaces.IIdentifierListener;
import com.bun.miitmdid.interfaces.IdSupplier;


public class MiitHelper implements IIdentifierListener {

    private AppIdsUpdater _listener;
    public MiitHelper(AppIdsUpdater callback){
        _listener=callback;

    }

    public void getDeviceIds(Context cxt){
        try {
            long timeb=System.currentTimeMillis();
            // 方法调用
            int nres = CallFromReflect(cxt);
            long timee=System.currentTimeMillis();
            long offset=timee-timeb;
            if(nres == ErrorCode.INIT_ERROR_DEVICE_NOSUPPORT){//不支持的设备
                Log.d("getDeviceIds","oaId=不支持的设备");
                if(_listener!=null) _listener.getIdError();
            }else if( nres == ErrorCode.INIT_ERROR_LOAD_CONFIGFILE){//加载配置文件出错
                Log.d("getDeviceIds","oaId=加载配置文件出错");
                if(_listener!=null) _listener.getIdError();
            }else if(nres == ErrorCode.INIT_ERROR_MANUFACTURER_NOSUPPORT){//不支持的设备厂商
                Log.d("getDeviceIds","oaId=不支持的设备厂商");
                if(_listener!=null) _listener.getIdError();
            }else if(nres == ErrorCode.INIT_ERROR_RESULT_DELAY){//获取接口是异步的，结果会在回调中返回，回调执行的回调可能在工作线程
                Log.d("getDeviceIds","oaId=结果会在回调中返回，回调执行的回调可能在工作线程");
                //if(_listener!=null) _listener.getIdError();
            }else if(nres == ErrorCode.INIT_HELPER_CALL_ERROR){//反射调用出错
                Log.d("getDeviceIds","oaId=反射调用出错");
                if(_listener!=null) _listener.getIdError();
            }
        }catch (Exception e){
            Log.d("getDeviceIds","oaId=异常");
            if(_listener!=null) _listener.getIdError();
        }
    }

    /*
     * 方法调用
     * */
    private int CallFromReflect(Context cxt){
        try {
            return MdidSdkHelper.InitSdk(cxt,true,this);
        }catch (Exception e){
            return ErrorCode.INIT_ERROR_DEVICE_NOSUPPORT;
        }
    }

    /*
     * 获取相应id
     * */
    @Override
    public void OnSupport(boolean isSupport, IdSupplier _supplier) {
        if(_supplier==null) {
            return;
        }
        String oaid=_supplier.getOAID();
        String vaid=_supplier.getVAID();
        String aaid=_supplier.getAAID();
//        StringBuilder builder=new StringBuilder();
//        builder.append("support: ").append(isSupport?"true":"false").append("\n");
//        builder.append("OAID: ").append(oaid).append("\n");
//        builder.append("VAID: ").append(vaid).append("\n");
//        builder.append("AAID: ").append(aaid).append("\n");

        if(_listener!=null) _listener.OnIdsAvalid(oaid,vaid,aaid);
    }

    public interface AppIdsUpdater{
        void OnIdsAvalid(String oaid, String vaid, String aaid);
        void getIdError();
    }

}
